package com.example.threadmodel.model;

import java.util.concurrent.atomic.AtomicBoolean;

public class SpinLock {
    private final AtomicBoolean atoLock = new AtomicBoolean();

    /**
     * 使用自旋锁时，必须保证传入的runnable执行时间很短
     * @param runnable 执行时间一定很短的行为
     */
    public void synchronizeExec(ShortTimeRunnable runnable) {
        do {
            if (atoLock.compareAndSet(false, true)) {
                try {
                    runnable.run();
                } finally {
                    atoLock.set(false);
                }
                return;
            }
        } while (true);
    }
}
